package com.dy.yunying.biz.service.prize.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.entity.hongbao.HbActivity;
import com.dy.yunying.api.entity.hongbao.HbSdkDynamicMenus;
import com.dy.yunying.api.entity.hongbao.PopupNotice;
import com.dy.yunying.api.entity.prize.PrizeConfig;
import com.dy.yunying.api.entity.prize.PrizeGiftBag;
import com.dy.yunying.api.entity.prize.PrizePush;
import com.dy.yunying.api.entity.sign.SignActivity;
import com.dy.yunying.api.enums.GiftTypeEnum;
import com.dy.yunying.api.enums.PrizeOpenTypeEnum;
import com.dy.yunying.api.enums.PrizePushHbTypeEnum;
import com.dy.yunying.api.enums.PrizeTypeEnum;
import com.dy.yunying.api.req.prize.PrizeConfigReq;
import com.dy.yunying.api.resp.prize.PrizeConfigRes;
import com.dy.yunying.biz.dao.ads.hongbao.HbActivityMapper;
import com.dy.yunying.biz.dao.ads.hongbao.HbSdkDynamicMenusMapper;
import com.dy.yunying.biz.dao.ads.hongbao.PopupNoticeMapper;
import com.dy.yunying.biz.dao.ads.prize.PrizeConfigMapper;
import com.dy.yunying.biz.dao.ads.prize.PrizeGiftBagMapper;
import com.dy.yunying.biz.dao.ads.prize.PrizePushMapper;
import com.dy.yunying.biz.service.hongbao.PopupNoticeService;
import com.dy.yunying.biz.service.prize.PrizeConfigService;
import com.dy.yunying.biz.service.prize.PrizeGiftBagService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.StringUtil;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * 奖励配置表
 *
 * @author chenxiang
 * @version 2022-04-25 16:25:44 table: prize_config
 */
@Log4j2
@Service("prizeConfigService")
@RequiredArgsConstructor
public class PrizeConfigServiceImpl extends ServiceImpl<PrizeConfigMapper, PrizeConfig> implements PrizeConfigService {

	private final HbSdkDynamicMenusMapper sdkDynamicMenusMapper;

	private final PrizeGiftBagService prizeGiftBagService;

	private final PrizePushMapper prizePushMapper;

	private final HbActivityMapper hbActivityMapper;

	private final PrizeGiftBagMapper prizeGiftBagMapper;

	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R<PrizeConfigRes> savePrizeConfig(PrizeConfigReq configReq) {
		String message = "创建/编辑奖励配置成功";
		String menuTitle = configReq.getMenuTitle();
		if (StringUtil.isNotBlank(configReq.getOpenType())) {
			PrizeOpenTypeEnum prizeOpenTypeEnum = PrizeOpenTypeEnum.getPrizeOpenTypeEnum(Integer.valueOf(configReq.getOpenType()));
			if (prizeOpenTypeEnum == PrizeOpenTypeEnum.SDK) {
				if (StringUtil.isNotBlank(menuTitle)) {
					R result = setMenuInfoToPrizeConfig(configReq, menuTitle);
					if (CommonConstants.FAIL.equals(result.getCode())) {
						return R.failed("无法获取SDK菜单数据");
					}
				}
			} else {
				configReq.setSkipUrlIOS(configReq.getSkipUrl());
			}
		}
		Integer prizeType = Integer.valueOf(configReq.getPrizeType());
		PrizeConfig prizeConfig = prizeConfigBean(configReq);
		//编辑
		if (prizeConfig.getId() != null) {
			//通过id查询出之前的
			PrizeConfig oldPrizeConfig = baseMapper.selectById(prizeConfig.getId());
			if (oldPrizeConfig != null) {
				PrizeTypeEnum newPrizeTypeEnum = PrizeTypeEnum.getPrizeTypeEnum(prizeConfig.getPrizeType());
				PrizeTypeEnum oldPrizeTypeEnum = PrizeTypeEnum.getPrizeTypeEnum(oldPrizeConfig.getPrizeType());
				if (oldPrizeTypeEnum != null && newPrizeTypeEnum != null && oldPrizeTypeEnum == newPrizeTypeEnum && (oldPrizeTypeEnum == PrizeTypeEnum.BAGCODE || oldPrizeTypeEnum == PrizeTypeEnum.CAMILO)) {
					if (!oldPrizeConfig.getGiftType().equals(prizeConfig.getGiftType())) {
						//礼包码类型不一样说明切换了
						//如果是从通用码切换成唯一码，删除之前通用码,将配置里面的通用码code置空
						if (GiftTypeEnum.COMMON.getType().equals(oldPrizeConfig.getGiftType()) && GiftTypeEnum.UNIQUE.getType().equals(prizeConfig.getGiftType())) {
							prizeGiftBagService.remove(Wrappers.<PrizeGiftBag>lambdaQuery().eq(PrizeGiftBag::getSourceId, prizeConfig.getId())
									.eq(PrizeGiftBag::getUsable, GiftTypeEnum.COMMON.getType()));
							//将之前删除的唯一码状态置为0
							prizeGiftBagMapper.updateDeleted(prizeConfig.getId(), GiftTypeEnum.UNIQUE.getType());
							prizeConfig.setGiftCode("");
							prizeConfig.setGiftAmount(null);
							baseMapper.updateGitCodeAndGitAmount(prizeConfig.getId());
						} else if (GiftTypeEnum.UNIQUE.getType().equals(oldPrizeConfig.getGiftType()) && GiftTypeEnum.COMMON.getType().equals(prizeConfig.getGiftType())) {
							//如果是唯一码切换成通用码
							//删除之前的唯一码
							prizeGiftBagService.remove(Wrappers.<PrizeGiftBag>lambdaQuery().eq(PrizeGiftBag::getSourceId, prizeConfig.getId())
									.eq(PrizeGiftBag::getUsable, GiftTypeEnum.UNIQUE.getType()));
						}
					}
				}
			}
		}
		if (StringUtils.isNotBlank(configReq.getPrizePushId())) {
			// 更新奖励推送表的更新时间，群组实时计算需要用到
			PrizePush prizePush = new PrizePush();
			prizePush.setId(Long.parseLong(configReq.getPrizePushId()));
			prizePush.setUpdateTime(new Date());
			prizePushMapper.updateById(prizePush);
		}
		this.saveOrUpdate(prizeConfig);
		// 处理礼包码逻辑
		String info = "";
		if (PrizeTypeEnum.CAMILO.getType().equals(prizeType) || PrizeTypeEnum.BAGCODE.getType().equals(prizeType)) {
			if (GiftTypeEnum.UNIQUE.getType().equals(Integer.valueOf(configReq.getGiftType()))
					&& configReq.getFile() != null) {
				R result = prizeGiftBagService.saveUniqueGiftBag(configReq.getFile(), prizeType, prizeConfig.getId());
				if (CommonConstants.FAIL.equals(result)) {
					return result;
				}
//				List<String> list = (List<String>) result.getData();
//				if (CollectionUtils.isNotEmpty(list)){
//					//更新prizeConfig的
//					prizeConfig.setGiftContent(String.join(",",list));
//					this.updateById(prizeConfig);
//				}
				info = result.getMsg();
			} else if (GiftTypeEnum.COMMON.getType().equals(Integer.valueOf(configReq.getGiftType()))) {
				prizeGiftBagService.saveCommonGiftBag(prizeConfig);
			}
		}
		PrizeConfigRes prizeConfigRes = new PrizeConfigRes();
		prizeConfigRes.setId(prizeConfig.getId());
		prizeConfigRes.setTitle(prizeConfig.getTitle());
		prizeConfigRes.setDescription(prizeConfig.getDescription());
		prizeConfigRes.setIcon(prizeConfig.getIcon());
		return R.ok(prizeConfigRes, message + info);
	}

	private R setMenuInfoToPrizeConfig(PrizeConfigReq configReq, String menuTitle) {
		String[] menuTitles = menuTitle.split(",");
		StringBuilder menuIds = new StringBuilder();
		StringBuilder skipUrl = new StringBuilder();
		StringBuilder skipUrlIOS = new StringBuilder();
		List<Long> menusCodeList = new ArrayList<>();
		String resourceLink = "";
		String resourceLinkIOS = "";
		if (StringUtil.isNotBlank(configReq.getSkipId())) {
			Integer skipId = Integer.valueOf(configReq.getSkipId());
			HbActivity hbActivity = hbActivityMapper.selectById(skipId);
			if (hbActivity != null) {
				configReq.setSkipBelongType(hbActivity.getActivityType() + "");
			}
		}
		if (menuTitles.length > 0) {
			String firstMenuTitle = menuTitles[0];
			List<HbSdkDynamicMenus> sdkDynamicMenusList = sdkDynamicMenusMapper.selectList(
					Wrappers.<HbSdkDynamicMenus>lambdaQuery().eq(HbSdkDynamicMenus::getMenuTitle, firstMenuTitle)
							.eq(HbSdkDynamicMenus::getStatus, 1).eq(HbSdkDynamicMenus::getDeleted, 0));
			if (CollectionUtils.isNotEmpty(sdkDynamicMenusList)) {
				for (HbSdkDynamicMenus sdkDynamicMenus : sdkDynamicMenusList) {
					if (2 == sdkDynamicMenus.getOsType()) {
						resourceLink = StringUtil.isNotBlank(sdkDynamicMenus.getResourceLink()) ? sdkDynamicMenus.getResourceLink() : "";
						if (Objects.nonNull(configReq.getSkipMold())) {
							if ("1".equals(configReq.getSkipMold())) {
								resourceLink = resourceLink.replace("#/activity", "#/redBag");
							} else if ("2".equals(configReq.getSkipMold())) {
								resourceLink = resourceLink.replace("#/activity", "#/signIn");
							}
						}
						configReq.setMenuCode(sdkDynamicMenus.getMenuCode());
						skipUrl.append("?")
								.append("menuCode")
								.append("=").append(sdkDynamicMenus.getMenuCode());
					} else if (3 == sdkDynamicMenus.getOsType()) {
						resourceLinkIOS = StringUtil.isNotBlank(sdkDynamicMenus.getResourceLink()) ? sdkDynamicMenus.getResourceLink() : "";
						if (Objects.nonNull(configReq.getSkipMold())) {
							if ("1".equals(configReq.getSkipMold())) {
								resourceLinkIOS = resourceLinkIOS.replace("/activity?", "/redBag?");
							} else if ("2".equals(configReq.getSkipMold())) {
								resourceLinkIOS = resourceLinkIOS.replace("/activity?", "/signIn?");
							}
						}
						configReq.setMenuCodeIos(sdkDynamicMenus.getMenuCode());
						skipUrlIOS.append("?")
								.append("menuCodeIos")
								.append("=").append(sdkDynamicMenus.getMenuCode());
					}
				}
			} else {
				return R.failed("无法获取SDK菜单数据");
			}
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("&sourceBelongType=").append(convertString(configReq.getSkipBelongType()))
				.append("&sourceId=").append(convertString(configReq.getSkipId()))
				.append("&activityId=").append(convertString(configReq.getSkipId()))
				.append("&sourceMold=").append(convertString(configReq.getSkipMold()));
		skipUrl.append(stringBuilder);
		skipUrlIOS.append(stringBuilder);
		configReq.setSkipUrl(resourceLink + skipUrl.toString());
		configReq.setSkipUrlIOS(resourceLinkIOS + skipUrlIOS.toString());
		return R.ok();
	}


	private String convertString(String str) {
		if (StringUtil.isNotBlank(str)) {
			if (!"0".equals(str)) {
				return str;
			}
		}
		return "";
	}

	@Override
	public R<List<PrizeConfigRes>> getAllPrizeConfig(PrizeConfigReq record) {
		List<PrizeConfigRes> result = new ArrayList<>();
		if (StringUtils.isBlank(record.getPrizePushId())) {
			return R.failed("奖励推送主键Id不存在");
		}
		if (StringUtils.isBlank(record.getPrizePushType())) {
			return R.failed("奖励推送类型不能为空");
		}

		List<PrizeConfig> list = this.list(Wrappers.<PrizeConfig>lambdaQuery().eq(PrizeConfig::getPrizePushId,
				Long.valueOf(record.getPrizePushId())).eq(PrizeConfig::getPrizePushType, Integer.valueOf(record.getPrizePushType())));
		list.forEach(prizeConfig -> {
			PrizeConfigRes prizeConfigRes = new PrizeConfigRes();
			BeanUtils.copyProperties(prizeConfig, prizeConfigRes);
			result.add(prizeConfigRes);
		});

		return R.ok(result);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R doRemoveById(Long id) {
		// 先判断配置是否存在
		List<PrizeConfig> prizeConfigs = baseMapper.selectList(
				Wrappers.<PrizeConfig>lambdaQuery().eq(PrizeConfig::getId, id).eq(PrizeConfig::getDeleted, 0));
		if (CollectionUtils.isEmpty(prizeConfigs)) {
			return R.failed("当前状态无法删除");
		}
		PrizeConfig prizeConfig = new PrizeConfig();
		prizeConfig.setId(id);
		prizeConfig.setUpdateTime(new Date());
		prizeConfig.setUpdateId(SecurityUtils.getUser().getId().longValue());
		// 删除配置
		baseMapper.update(prizeConfig,
				Wrappers.<PrizeConfig>lambdaUpdate().eq(PrizeConfig::getId, id).set(PrizeConfig::getDeleted, 1));
		// 删除礼包
		if (GiftTypeEnum.UNIQUE.getType().equals(prizeConfigs.get(0).getGiftType())) {
			prizeGiftBagService.remove(Wrappers.<PrizeGiftBag>lambdaQuery().eq(PrizeGiftBag::getSourceId, id)
					.eq(PrizeGiftBag::getDeleted, 0));
		}
		// 更新奖励推送表的更新时间，群组实时计算需要用到
		PrizePush prizePush = new PrizePush();
		prizePush.setId(prizeConfigs.get(0).getPrizePushId());
		prizePush.setUpdateTime(new Date());
		prizePushMapper.updateById(prizePush);
		return R.ok();
	}

	private PrizeConfig prizeConfigBean(PrizeConfigReq configReq) {
		PrizeConfig prizeConfig = new PrizeConfig();
		BeanUtils.copyProperties(configReq, prizeConfig);
		if (StringUtil.isBlank(prizeConfig.getMenuTitle())) {
			prizeConfig.setMenuId("");
		}
		prizeConfig.setGiftContent("");
		prizeConfig.setId(StringUtil.isNotBlank(configReq.getId()) ? Long.valueOf(configReq.getId()) : null);
		prizeConfig.setPrizePushId(StringUtil.isNotBlank(configReq.getPrizePushId()) ? Long.valueOf(configReq.getPrizePushId()) : null);
		prizeConfig.setPrizePushType(StringUtil.isNotBlank(configReq.getPrizePushType()) ? Integer.valueOf(configReq.getPrizePushType()) : 1);
		prizeConfig.setPrizeButton(StringUtil.isNotBlank(configReq.getPrizeButton()) ? Integer.valueOf(configReq.getPrizeButton()) : null);
		prizeConfig.setPrizeType(StringUtil.isNotBlank(configReq.getPrizeType()) ? Integer.valueOf(configReq.getPrizeType()) : null);
		prizeConfig
				.setMoney(StringUtil.isNotBlank(configReq.getMoney()) ? new BigDecimal(configReq.getMoney()) : null);
		prizeConfig.setLimitMoney(
				StringUtil.isNotBlank(configReq.getLimitMoney()) ? new BigDecimal(configReq.getLimitMoney()) : null);
		prizeConfig.setTimeType(
				StringUtil.isNotBlank(configReq.getTimeType()) ? Integer.valueOf(configReq.getTimeType()) : 1);
		prizeConfig.setStartTime(DateUtils.stringToDate(configReq.getStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		prizeConfig.setEndTime(DateUtils.stringToDate(configReq.getEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		prizeConfig.setEffectiveTime(StringUtil.isNotBlank(configReq.getEffectiveTime())
				? Long.valueOf(configReq.getEffectiveTime()) : null);
		prizeConfig.setGiftType(
				StringUtil.isNotBlank(configReq.getGiftType()) ? Integer.valueOf(configReq.getGiftType()) : null);
		prizeConfig.setGiftAmount(
				StringUtil.isNotBlank(configReq.getGiftAmount()) ? Integer.valueOf(configReq.getGiftAmount()) : null);
		prizeConfig.setOpenType(
				StringUtil.isNotBlank(configReq.getOpenType()) ? Integer.valueOf(configReq.getOpenType()) : null);
		prizeConfig
				.setMenuId(configReq.getMenuId());
		prizeConfig.setSkipMold(
				StringUtil.isNotBlank(configReq.getSkipMold()) ? Integer.valueOf(configReq.getSkipMold()) : null);
		prizeConfig
				.setSkipId(StringUtil.isNotBlank(configReq.getSkipId()) ? Long.valueOf(configReq.getSkipId()) : null);
		prizeConfig.setSkipBelongType(StringUtil.isNotBlank(configReq.getSkipBelongType()) ? Integer.valueOf(configReq.getSkipBelongType()) : null);
		prizeConfig.setCurrencyType(StringUtil.isNotBlank(configReq.getCurrencyType()) ? Integer.valueOf(configReq.getCurrencyType()) : null);
		prizeConfig.setShowType(
				StringUtil.isNotBlank(configReq.getShowType()) ? Integer.valueOf(configReq.getShowType()) : null);


		if (StringUtil.isBlank(configReq.getId())) {
			prizeConfig.setCreateTime(new Date());
			prizeConfig.setCreateId(SecurityUtils.getUser().getId().longValue());
		} else {
			prizeConfig.setUpdateTime(new Date());
			prizeConfig.setUpdateId(SecurityUtils.getUser().getId().longValue());
		}
		return prizeConfig;
	}

}
